package cn.codingjc.peekaboo.application.core.pipeline;

import cn.codingjc.peekaboo.application.util.MessageUtils;
import cn.codingjc.peekaboo.domain.domain.sys.vo.ResultVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 处理控制器
 * @date: 2023/5/4
 * @author: Codingjc
 * @className: ProcessController
 **/

@Data
@Slf4j
public class ProcessController {

    private Map<String, ProcessTemplate> processTemplateMap = null;

    public ProcessContext process(ProcessContext context){
        if (!checkPre(context)) {
            return context;
        }

        ProcessTemplate processTemplate = processTemplateMap.get(context.getCode());
        for (BusinessProcess businessProcess : processTemplate.getBusinessProcesses()) {
            businessProcess.process(context);
            if (context.getNeedBreak()) {
                break;
            }
        }
        return context;
    }

    /**
     * 前置校验
     * @param context
     * @return
     */
    private boolean checkPre(ProcessContext context) {
        if (context == null) {
            context = new ProcessContext();
            context.setResult(ResultVO.fail(MessageUtils.getMessage("context.is.null")));
            return false;
        }

        if (StringUtils.isEmpty(context.getCode())) {
            context.setResult(ResultVO.fail(MessageUtils.getMessage("context.code.is.null")));
            return false;
        }

        if (processTemplateMap == null) {
            context.setResult(ResultVO.fail(MessageUtils.getMessage("process.template.is.null")));
            return false;
        }

        ProcessTemplate processTemplate = processTemplateMap.get(context.getCode());
        if (processTemplate == null) {
            context.setResult(ResultVO.fail(MessageUtils.getMessage("process.template.is.null")));
            return false;
        }
        return true;
    }
}
